package com.anolesoft.secondaryCostAccounting.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.anolesoft.common.core.constant.HttpStatus;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.secondaryCostAccounting.dto.*;
import com.anolesoft.secondaryCostAccounting.service.MatchService;
import com.anolesoft.secondaryCostAccounting.util.NumStringUtil;
import com.anolesoft.secondaryCostAccounting.util.SqlserverData;
import com.anolesoft.yr.demo.PageResult;
import com.anolesoft.yr.util.PageData;
import com.anolesoft.yr.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping(value = "/matchInfo")
@Slf4j
public class MatchInfoController {

    @Autowired
    MatchService matchService;

    /**
     * 上下总面板查询
     * @param matchConditionDTO
     * @return
     */
    @PostMapping(value = "/query")
    public AjaxResult queryMatchInfo(@RequestBody MatchConditionDTO matchConditionDTO){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        matchConditionDTO.setFactoryId(loginUser.getFacCode());
        log.debug("matchConditionDTO:{}",matchConditionDTO);
        PageData<List<MatchDO>> matchInfo = matchService.queryMatchInfo(matchConditionDTO,false);
        //PageData<List<MatchDO>> matchInfo = matchService.queryMatchInfo(matchConditionDTO);
        System.out.println(">>>matchCondition:" + matchInfo.getTotal());
        PageResult pageResult = new PageResult(matchInfo.getItems(),matchConditionDTO.getPageSize(),matchConditionDTO.getPageNo(),matchInfo.getTotal());
        AjaxResult success = AjaxResult.success();
        success.put("result",pageResult);
        return success;
    }

    /**
     * 匹配页面数据
     * @param matchInfoDTO
     * @return
     */
    @PostMapping(value = "/scaCondition", produces = MediaType.APPLICATION_JSON_VALUE)
    public AjaxResult matchSCA(@RequestBody MatchInfoDTO matchInfoDTO){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        matchInfoDTO.setFactoryId(loginUser.getFacCode());
        SqlserverData sqlserverData = matchService.matchSCA(matchInfoDTO);
        //try {
        //    Thread.sleep(1000);
        //} catch (InterruptedException e) {
        //    e.printStackTrace();
        //}
        //AjaxResult success = AjaxResult.success();
        //success.put("result",scAccount);
        return AjaxResult.success("查询成功",sqlserverData);
    }

    /**
     * 获取匹配数据数量 已弃用
     * @param matchInfoDTO
     * @return
     */
    //@PostMapping(value = "/matchNum", produces = MediaType.APPLICATION_JSON_VALUE)
    //public AjaxResult matchNum(@RequestBody MatchInfoDTO matchInfoDTO){
    //    int temp = matchService.matchNum(matchInfoDTO);
    //    String num = String.valueOf(temp);
    //    return new AjaxResult(HttpStatus.SUCCESS, num);
    //}

    /**
     * 将匹配结果存入表中
     * @param sqlserverData
     * @return
     */
    @PostMapping(value = "/updateMatch", produces = MediaType.APPLICATION_JSON_VALUE)
    public AjaxResult updateMatch(@RequestBody SqlserverData sqlserverData){
        List<SCAccountingDTO> scAccountingDTOS = sqlserverData.getData();
        if (sqlserverData.getGongduan().equals("null")) {
            return AjaxResult.error("未获取到二级成本核算对应的工段班组数据！");
        }
        EmployeeFromSCADTO employee = EmployeeFromSCADTO.builder()
                .gongduan(sqlserverData.getGongduan())
                .banzu(sqlserverData.getBanzu())
                .build();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String total = "0";
        NumStringUtil numStringUtil = new NumStringUtil();
        for (int i = 0; i < scAccountingDTOS.size(); i++) {
            scAccountingDTOS.get(i).setCreateId(loginUser.getEmpUid());
            scAccountingDTOS.get(i).setFactoryId(loginUser.getFacCode());
            total = numStringUtil.numAdd(total,scAccountingDTOS.get(i).getBangdingnum());
        }
        String result = matchService.updateMatch(scAccountingDTOS, total, employee);
        return AjaxResult.success("匹配成功", result);
    }

    @PostMapping(value = "/queryPrint")
    public AjaxResult queryPrint(@RequestBody String[] objuids){
        StringBuffer str = new StringBuffer();
        if (objuids != null && objuids.length > 0) {
            int length = objuids.length;
            for (int i = 0; i < length; i++) {
                String s = objuids[i];
                if (i < length - 1) {
                    str.append("'" + s + "',");
                } else {
                    str.append("'" + s + "'");
                }
            }
        }
        log.debug("字符串数组转字符串结果：" + str.toString());
        List<MesAccountMatchPrintDTO> matchPrintDTOS = this.matchService.queryPrint(str.toString());
        return AjaxResult.success(matchPrintDTOS);
    }

    /**
     * 导出到excel
     * @param matchConditionDTO
     * @param response
     */
    @PostMapping(value="/export")
    public void queryMatchExport(@RequestBody MatchConditionDTO matchConditionDTO, HttpServletResponse response){
        long start = System.currentTimeMillis();
        //OutputStream output = null;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        matchConditionDTO.setFactoryId(loginUser.getFacCode());
        try {
            OutputStream output = response.getOutputStream();
            //字符集
            response.setCharacterEncoding("utf-8");
            //类型
            response.setContentType("multipart/form-data");
            //响应头
            response.setHeader("Content-Disposition", "attachment;filename="+new String(("exportMatch.xlsx").getBytes("gb2312"),"ISO8859-1"));
            String[] objuids = matchConditionDTO.getSelect();
            if (objuids != null) {
                StringBuffer str = new StringBuffer();
                if (objuids != null && objuids.length > 0) {
                    int length = objuids.length;
                    for (int i = 0; i < length; i++) {
                        String s = objuids[i];
                        if (i < length - 1) {
                            str.append("'" + s + "',");
                        } else {
                            str.append("'" + s + "'");
                        }
                    }
                }
                log.debug("字符串数组转字符串结果：" + str.toString());
                matchConditionDTO.setObjuid(str.toString());
            }
            log.debug("条件：{}",matchConditionDTO);
            //总条数
            int total = matchService.countExport(matchConditionDTO);
            log.debug("total:" + total);
            //单个sheet最大条数
            int size = 100000;
            //sheet数
            int sheet = total / size + 1;
            //单次查询条数
            int pageSize = 1000;
            ExcelWriter excelWriter = EasyExcel.write(output).build();
            //执行查询次数
            int count = 1;
            for (int i = 0; i < sheet ; i++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i,"出库单" + (i+1))
                        .head(MatchExport.class)
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .build();
                int rolling;
                if (i == sheet - 1) {
                    rolling = (total - i * size) / pageSize + 1;
                } else {
                    rolling = size / pageSize;
                }
                for (int j = 0; j < rolling; j++) {
                    matchConditionDTO.setPageNo(count);
                    matchConditionDTO.setPageSize(pageSize);
                    PageData<List<MatchDO>> matchInfo = matchService.queryMatchInfo(matchConditionDTO,true);
                    //PageData<List<MatchDO>> matchInfo = matchService.queryMatchInfo(matchConditionDTO);
                    List<MatchExport> datas = matchInfo.getItems().stream().map(item -> {
                        MatchExport matchExport = new MatchExport();
                        BeanUtils.copyProperties(item, matchExport);
                        return matchExport;
                    }).collect(Collectors.toList());
                    excelWriter.write(datas, writeSheet);
                    count++;
                }
            }
            log.debug("查询次数：" + (count - 1) + "次");
            //刷新流
            excelWriter.finish();
            output.flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            log.error("导出失败：{}", e.getMessage());
            e.printStackTrace();
        } finally {
            long end = System.currentTimeMillis();
            log.debug("总用时：" + (end - start) + "毫秒");
        }
    }

    /**
     * 百万级数据导出测试方法
     * @param matchConditionDTO
     * @param response
     */
    //@PostMapping(value="/export")
    //public void queryMatchExport(@RequestBody MatchConditionDTO matchConditionDTO, HttpServletResponse response){
    //    long start = System.currentTimeMillis();
    //    //OutputStream output = null;
    //    LoginUser loginUser = SecurityUtils.getLoginUser();
    //    matchConditionDTO.setFactoryId(loginUser.getFacCode());
    //    try {
    //        OutputStream output = response.getOutputStream();
    //        //字符集
    //        response.setCharacterEncoding("utf-8");
    //        //类型
    //        response.setContentType("multipart/form-data");
    //        //响应头
    //        response.setHeader("Content-Disposition", "attachment;filename="+new String(("exportMatch.xlsx").getBytes("gb2312"),"ISO8859-1"));
    //        //总条数
    //        int total = matchService.countExport(matchConditionDTO);
    //        log.debug("total:" + total);
    //        //单个sheet最大条数
    //        //int size = 100000;
    //        //sheet数
    //        //int sheet = total / size + 1;
    //        //单次查询条数
    //        //int pageSize = 1000;
    //        ExcelWriter excelWriter = EasyExcel.write(output).build();
    //        //执行查询次数
    //        int count = 1;
    //        for (int i = 0; i < 10 ; i++) {
    //            WriteSheet writeSheet = EasyExcel.writerSheet(i,"出库单" + (i+1))
    //                    .head(MatchExport.class)
    //                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
    //                    .build();
    //            //int rolling;
    //            //if (i == 10 - 1) {
    //            //    rolling = (total - i * size) / pageSize + 1;
    //            //} else {
    //            //    rolling = size / pageSize;
    //            //}
    //            for (int j = 0; j < 100; j++) {
    //                matchConditionDTO.setPageNo(1);
    //                matchConditionDTO.setPageSize(1000);
    //                PageData<List<MatchDO>> matchInfo = matchService.queryMatchInfo(matchConditionDTO);
    //                List<MatchExport> datas = matchInfo.getItems().stream().map(item -> {
    //                    MatchExport matchExport = new MatchExport();
    //                    BeanUtils.copyProperties(item, matchExport);
    //                    return matchExport;
    //                }).collect(Collectors.toList());
    //                excelWriter.write(datas, writeSheet);
    //                count++;
    //            }
    //        }
    //        log.debug("查询次数：" + (count - 1) + "次");
    //        //刷新流
    //        excelWriter.finish();
    //        output.flush();
    //        response.getOutputStream().close();
    //    } catch (Exception e) {
    //        log.error("导出失败：{}", e.getMessage());
    //        e.printStackTrace();
    //    } finally {
    //        long end = System.currentTimeMillis();
    //        log.debug("总用时：" + (end - start) + "毫秒");
    //    }
    //}
}
